import React from 'react';
import PropTypes from 'prop-types';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import { Row, Col, Button, Popconfirm } from 'antd';
import List from './List';
import Filter from './Filter';
import Modal from './Modal';

const SysConfig = ({ location, dispatch, sysConfig, loading }) => {
	const { list, pagination, currentItem, modalVisible, modalType, isMotion, selectedRowKeys } = sysConfig;

	const modalProps = {
		item: modalType === 'create' ? {} : currentItem,
		visible: modalVisible,
		maskClosable: false,
		confirmLoading: loading.effects['sysConfig/update'],
		title: `${modalType === 'create' ? '添加' : '更新'}`,
		wrapClassName: 'vertical-center-modal',
		onOk(data) {
			dispatch({
				type: `sysConfig/${modalType}`,
				payload: data,
			});
		},
		onCancel() {
			dispatch({
				type: 'sysConfig/hideModal',
			});
		},
	};

	const handleFields = (fields) => {
		const { createTime } = fields;
		if (createTime.length) {
			fields.startTime = createTime[0].format('YYYY-MM-DD HH:mm:ss');
			fields.endTime = createTime[1].format('YYYY-MM-DD HH:mm:ss');
		}
		for (const k in fields) {
			if (!fields[k]) delete fields[k];
		}
		delete fields.createTime;
		return fields;
	};

	const listProps = {
		dataSource: list,
		loading: loading.effects['sysConfig/query'],
		pagination,
		location,
		isMotion,
		onChange({ current, pageSize }) {
			const { query, pathname } = location;

			dispatch(routerRedux.push({
				pathname,
				query: {
					...query,
					current,
					size: pageSize
				},
			}));
		},
		onDeleteItem(id) {
			dispatch({
				type: 'sysConfig/delete',
				payload: id,
			});
		},
		onEditItem(item) {
			dispatch({
				type: 'sysConfig/showModal',
				payload: {
					modalType: 'update',
					currentItem: item,
				},
			});
		},
		rowSelection: {
			selectedRowKeys,
			onChange: (keys) => {
				dispatch({
					type: 'sysConfig/updateState',
					payload: {
						selectedRowKeys: keys,
					},
				});
			},
		},
	};

	const filterProps = {
		isMotion,
		filter: {
			...location.query,
		},
		onFilterChange(value) {
			const { startTime, endTime, ...condition } = handleFields(value);
			dispatch(routerRedux.push({
				pathname: location.pathname,
				query: {
					current: 1,
					condition: JSON.stringify(condition),
					startTime,
					endTime
				},
			}));
		},
		onAdd() {
			dispatch({
				type: 'sysConfig/showModal',
				payload: {
					modalType: 'create',
				},
			});
		},
		switchIsMotion() {
			dispatch({ type: 'sysConfig/switchIsMotion' });
		},
	};

	return (
		<div className="content-inner">
			<Filter {...filterProps} />
			<List {...listProps} />
			{modalVisible && <Modal {...modalProps} />}
		</div>
	);
};

SysConfig.propTypes = {
	sysConfig: PropTypes.object,
	location: PropTypes.object,
	dispatch: PropTypes.func,
	loading: PropTypes.object,
};

export default connect(({ sysConfig, loading }) => ({ sysConfig, loading }))(SysConfig);
